<!--文件选择器-->
<template>
  <div class="file-choose-container">
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      class="file-choose-dialog"
      :title="title"
      width="830px"
      :append-to-body="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true">
      <div class="file-choose-dialog-body">
        <!--左侧目录-->
        <div class="file-catalog">
          <el-tree
            ref="fileTree"
            v-loading="treeLoading"
            class="common-el-tree scrollbar-no-width tree-active"
            node-key="id"
            :default-expanded-keys="expandedKeys"
            :props="fileCatalogProps"
            :load="loadFileCatalog"
            lazy
            @node-click="handleCatalogNodeClick">
            <div slot-scope="{ node,data }" class="custom-tree-node">
              <file-catalog-svg-icon :type="data.catalogType" />
              <span class="text">{{ node.label }}</span>
            </div>
          </el-tree>
        </div>
        <!--文件-->
        <div class="file-container">
          <el-empty v-if="list.length===0" description="此文件夹下暂无文件资源" />
          <div v-else class="file-list-warp">
            <div class="file-choose-list">
              <div v-for="file in list" :key="file.id" class="list-item" @mouseenter="mouseEnter(file)" @mouseleave="mouseLeave(file)" @click="handleSelectFile(file)">
                <div class="img">
                  <el-image
                    v-if="file.type===1"
                    style="width: 100px; height: 100px"
                    :src="common.getFileView(file.uuid)"
                    fit="contain" />
                  <FileTypeSvgIcon v-else :type="file.type" :size="56" />
                </div>
                <div class="name" :title="file.originalName">{{ file.originalName }}</div>
                <div v-if="file.toolShow" class="tools">
                  <el-link type="primary" :underline="false" @click.stop="handleRename(file)">重命名</el-link>
                  <fileViewer :type="file.type" :url="file.uuid" :title="file.originalName" mode="page">
                    <el-link type="primary" :underline="false">预览</el-link>
                  </fileViewer>
                </div>
                <div v-if="file.checked" class="has-select-file">
                  <i class="el-icon-check" />
                </div>
                <el-link v-if="file.toolShow" class="file-remove" type="primary" :underline="false" @click.native="handleRemoveFile(file)">
                  <i class="el-icon-close" />
                </el-link>
              </div>
            </div>
            <div class="pagination_handler">
              <pagination v-show="total>12" layout="total, prev, pager, next" :background="false" :page-sizes="[12]" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchFile" />
            </div>
          </div>
        </div>
        <!--已选文件-->
        <div class="file-has-choose-container">
          <div class="file-choose-header">
            <span>已选择 {{ selectedList.length }}/{{ limit }}</span>
            <el-link type="primary" :underline="false" @click.native="handleClearSelecedFile(file)">清空</el-link>
          </div>
          <div class="file-select-list">
            <div v-for="file in selectedList" :key="file.id" class="select-item" @mouseenter="mouseSelectedEnter(file)" @mouseleave="mouseSelectedLeave(file)">
              <div class="img">
                <el-image
                  v-if="file.type===1"
                  style="width: 100px; height: 100px"
                  :src="common.getFileView(file.uuid)"
                  fit="contain" />
                <FileTypeSvgIcon v-else :type="file.type" :size="56" />
              </div>
              <el-link v-if="file.toolShow" class="file-remove" type="primary" :underline="false" @click.native="handleRemoveSelectFile(file)">
                <i class="el-icon-close" />
              </el-link>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfimSelect">确 定</el-button>
      </span>
    </el-dialog>
    <!--重命名-->
    <el-dialog :visible.sync="renameVisible" :close-on-click-modal="false" title="重命名" width="500px">
      <el-input v-model="recordForm.originalName" placeholder="请输入名称" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="renameVisible = false">取消</el-button>
        <el-button type="primary" @click="doRename">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: {
    // 文件夹
    catalog: {
      type: String,
      default: null
    },
    limit: {
      type: Number,
      default: 1
    },
    // file:所有文件 img：图片 doc：word文档 xls：电子表格 ppt：演示文稿  office：办公文档 pdf：PDF  voice：音频 video：视频
    type: {
      type: String,
      default: 'file'
    },
    // record:完整记录  uuid:文件uuid
    emitMode: {
      type: String,
      default: 'file'
    }
  },
  data() {
    return {
      catalogId: null,
      dialogVisible: false,
      title: '选择图片',
      treeLoading: false,
      fileCatalogProps: {
        label: 'catalogName',
        children: 'catalogs',
        isLeaf: 'leaf'
      },
      expandedKeys: [],
      selectedNode: {},
      selectedResolve: {},
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 12,
        keyword: null,
        sort: '-gmtCreated'
      },
      renameVisible: false,
      recordForm: {},
      selectedList: []
    }
  },
  watch: {
    catalogId(val) {
      this.handleFilter()
    }
  },
  created() {
  },
  methods: {
    /**
     * @description: 打开选择器启动方法
     * @param {params} 参数
     */
    openChoose(params = {}) {
      this.handleChooseFile()
    },
    clearChoose() {
      this.selectedList = []
    },
    mouseEnter(data) {
      this.$set(data, 'toolShow', true)
    },
    mouseLeave(data) {
      this.$set(data, 'toolShow', false)
    },
    mouseSelectedEnter(data) {
      this.$set(data, 'toolShow', true)
    },
    mouseSelectedLeave(data) {
      this.$set(data, 'toolShow', false)
    },
    async loadFileCatalog(node, resolve) {
      this.selectedResolve = resolve
      try {
        this.treeLoading = true
        if (node.level === 0) {
          if (this.catalog) {
            const catalogResponse = await this.$store.dispatch('getFileCatalogById', this.catalog)
            console.log(catalogResponse)
            if (!catalogResponse) {
              resolve([])
            } else {
              this.expandedKeys.push(catalogResponse.id)
              this.$nextTick(() => {
                this.catalogId = catalogResponse.id
              })
              resolve([catalogResponse])
            }
          } else {
            const catalogResponse = await this.$store.dispatch('listFileSystemCatalog')
            if (catalogResponse.length === 0) {
              this.$message.danger('系统还初始化文件目录,请联系管理员初始化目录')
            } else {
              var temp = catalogResponse[0]
              this.expandedKeys.push(temp.id)
              this.$nextTick(() => {
                this.catalogId = temp.id
              })
            }
            resolve(catalogResponse)
          }
        } else {
          const catalogResponse = await this.$store.dispatch('listFileCatalogByPid', { pid: node.data.id })
          resolve(catalogResponse)
        }
        this.treeLoading = false
      } catch (err) {
        console.log(err)
      }
    },
    /* 搜索*/
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        sort: '-gmtCreated',
        page: 1
      }
      this.fetchFile()
      this.$nextTick(() => {
        this.$refs.fileTree.setCurrentKey(this.catalogId)
      })
    },
    fetchFile() {
      if (!this.catalogId) {
        this.list = []
        this.total = []
        return
      }
      // 文件类型  1：图片 2.word文档 3.电子表格 4.演示文稿 7.PDF 8.mp3 9.mp4
      // file:所有文件 img：图片 doc：word文档 xls：电子表格 ppt：演示文稿  office：办公文档 pdf：PDF  voice：音频 video：视频
      var fileType = null
      if (this.type === 'img') {
        fileType = '1'
        this.title = '选择图片'
      } else if (this.type === 'doc') {
        fileType = '2'
        this.title = '选择Word文档'
      } else if (this.type === 'xls') {
        fileType = '3'
        this.title = '选择电子表格'
      } else if (this.type === 'ppt') {
        fileType = '4'
        this.title = '选择演示文稿'
      } else if (this.type === 'office') {
        fileType = '2,3,4'
        this.title = '选择办公文件'
      } else if (this.type === 'pdf') {
        fileType = '7'
        this.title = '选择PDF'
      } else if (this.type === 'voice') {
        fileType = '8'
        this.title = '选择音频'
      } else if (this.type === 'video') {
        fileType = '9'
        this.title = '选择视频'
      } else {
        this.title = '选择文件'
      }
      this.listQuery = {
        ...this.listQuery,
        catalogId: this.catalogId,
        fileType: fileType
      }
      this.$store.dispatch('currentUserFilePage', this.listQuery).then(res => {
        this.list = res.records
        this.total = res.total
        this.handleFileChecked()
      })
    },
    handleCatalogNodeClick(data, node) {
      // this.getFullPath(data.id)
      this.$nextTick(() => {
        this.catalogId = data.id
        this.selectedNode = node
      })
    },
    handleChooseFile() {
      this.dialogVisible = true
      this.handleFilter()
    // this.selectedList = []
    },
    handleClose(done) {
      this.$confirm('确认关闭?').then(_ => {
        done()
        this.handleCancel()
      }).catch(_ => {})
    },
    handleCancel() {
      this.dialogVisible = false
    },
    handleConfimSelect() {
      if (this.selectedList.length === 0) {
        this.$message.warning('请选择文件')
        return
      }
      this.dialogVisible = false
      if (this.limit === 1) {
        if (this.emitMode === 'uuid') {
          this.$emit('chooseResult', this.selectedList[0].uuid)
        } else {
          this.$emit('chooseResult', this.selectedList[0])
        }
      } else {
        if (this.emitMode === 'uuid') {
          var uuids = []
          this.selectedList.forEach(item => {
            uuids.push(item.uuid)
          })
          this.$emit('chooseResult', uuids)
        } else {
          this.$emit('chooseResult', this.selectedList)
        }
      }
    },
    handleSelectFile(file) {
      var item = Object.assign({}, file)
      if (this.limit > 1) {
        if (file.checked === true) {
          console.log('移除')
          this.selectedList = this.selectedList.filter(item => {
            return item.id !== file.id
          })
        } else {
          if (this.selectedList.length >= this.limit) {
            this.$message.warning('已达到文件选择上限')
            return
          }
          this.selectedList.push(item)
        }
      } else {
        this.list.forEach(item => {
          item.checked = false
        })
        this.selectedList = [item]
      }

      this.$set(file, 'checked', !file.checked)
    },
    handleRename(file) {
      this.recordForm = {
        id: file.id,
        originalName: file.originalName
      }
      this.renameVisible = true
    },
    doRename() {
      if (!this.recordForm.originalName) {
        this.$message.warning('请输入文件名称')
        return
      }
      this.$store.dispatch('fileResourcesRename', this.recordForm).then(response => {
        this.renameVisible = false
        this.$modal.msgSuccess('文件重命名成功')
        this.fetchFile()
      }).catch(() => {
      })
    },

    handleRemoveFile(file) {
      this.$confirm(`确认删除后，本地或云存储文件【${file.originalName}】也将同步删除，如文件已被使用，请谨慎操作, 是否继续?`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('fileResourcesRemove', file.uuid).then(response => {
          this.$modal.msgSuccess('操作成功')
          this.handleFilter()
        }).catch(() => {})
      }).catch(() => {})
    },
    handleFileChecked() {
      var selectFileIds = []
      this.selectedList.forEach(item => {
        selectFileIds.push(item.id)
      })
      this.list.forEach(item => {
        item.checked = selectFileIds.includes(item.id)
      })
    },
    handleClearSelecedFile() {
      if (this.selectedList.length === 0) {
        return
      }
      this.$confirm(`您确定清除全部选择的文件, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectedList = []
        this.handleFileChecked()
      }).catch(() => {})
    },
    handleRemoveSelectFile(file) {
      this.selectedList = this.selectedList.filter(item => {
        return item.id !== file.id
      })
      this.handleFileChecked()
    }
  }
}
</script>
<style lang="scss">
  .file-choose-dialog{
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
    .el-dialog {
      margin: 0 auto !important;
      overflow: hidden;
      .el-dialog__body {
        max-height: calc(100vh - 200px);
        z-index: 1;
        border: 1px solid #ebeef5;
        padding: 0;
        overflow: hidden;
        overflow-y: auto;
      }
    }
  }
 .file-choose-dialog-body{
    display: flex;
    flex-direction: row;
    height: 430px;
    .file-catalog{
      width: 178px;
      overflow: auto;
    }
    .file-catalog::-webkit-scrollbar {
      width: 0px;
      height: 0px;
    }
    .file-container{
      flex: 1;
      border-right:1px solid #ebeef5 ;
      border-left: 1px solid #ebeef5;
      overflow: auto;
      display: flex;
      flex-direction: column;
      .file-list-warp{
        overflow: auto;
        display: flex;
        flex-direction: column;
        flex: 1;
      }
      .file-choose-list{
        overflow: auto;
        padding: 10px 8px;
        flex: 1;
        .list-item {
          height: 167px;
          position: relative;
          vertical-align: top;
          margin: 0 8px;
          cursor: pointer;
          display: inline-block;
          display: inline-block;
          .img {
            width: 100px;
            height: 100px;
            background-repeat: no-repeat;
            background-position: center;
            background-color: #f2f2f2;
            border: 1px solid #f2f2f2;
            background-size: cover;
            border-radius: 3px;
            overflow: hidden;
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;
            img{
              width: 100%;
            }
          }
          .name {
            width: 100px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: #333;
            font-size: 12px;
            text-align: center;
            margin-top: 12px;
          }
          .tools{
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            margin-top: 3px;
            a{
              font-size: 12px;
            }
          }
          .file-remove{
            top: -8px;
            right: -8px;
            width: 16px;
            height: 16px;
            background-color: #0000004d;
            justify-content: center;
            align-items: center;
            border-radius: 50%;
            color: #fff;
            cursor: pointer;
            position: absolute;
            i{
              color: #fff;
              font-size: 11px;
            }
          }
          .has-select-file{
            display: flex;
            align-items: center;
            justify-content: center;
            position: absolute;
            top: 0;
            left: 0;
            width: 100px;
            height: 100px;
            border-radius: 4px;
            background-color: #00000080;
            box-sizing: border-box;
            i{
              color: #fff;
              font-size: 20px;
            }
          }
        }
      }
    }
    .file-choose-list::-webkit-scrollbar {
      width: 0px;
      height: 0px;
    }
    .file-has-choose-container{
      width: 130px;
      display: flex;
      flex-direction: column;
      .file-choose-header{
        padding: 8px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
      }
      .file-select-list::-webkit-scrollbar {
        width: 0px;
        height: 0px;
      }
      .file-select-list{
        flex: 1;
        overflow: auto;
        display: flex;
        flex-direction: column;
        padding-top: 7px;
        .select-item{
          position: relative;
          vertical-align: top;
          margin: 0 8px 16px 8px;
          cursor: pointer;
          display: flex;
          flex-direction: row;
          justify-content: center;
          .img {
            width: 100px;
            height: 100px;
            background-repeat: no-repeat;
            background-position: center;
            background-color: #f2f2f2;
            border: 1px solid #f2f2f2;
            background-size: cover;
            border-radius: 3px;
            overflow: hidden;
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;
            img{
              width: 100%;
            }
          }
        }
        .file-remove{
          top: -7px;
          right: -1px;
          width: 16px;
          height: 16px;
          background-color: #0000004d;
          justify-content: center;
          align-items: center;
          border-radius: 50%;
          color: #fff;
          cursor: pointer;
          position: absolute;
          i{
            color: #fff;
            font-size: 11px;
          }
        }
      }
    }
  }
.file-choose-container{
  display: inline;
  .file-show-list{
    .file-show-item{
      margin-right: 10px;
      float: left;
      margin-bottom: 10px
    }
  }
  .file-show-item{
    border: 1px dashed #097aff;
    color: #097aff;
    border-radius: 4px;
    justify-content: center;
    align-items: center;
    display: flex;
    flex-direction: row;
    cursor: pointer;
    i{
      font-size: 25px;
    }
  }
  .file-wrap{
    width: 96px;
    height: 96px;
    display: flex;
    flex-direction: column;
    span{
      text-align: center;
    }
    .file-title{
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      width: 96px;
      padding: 0px 8px;
      text-align: center;
    }
  }
}
</style>
